package com.ds.esd.admin.plugins.service;

import com.alibaba.fastjson.JSON;
import com.ds.cluster.service.SysEventWebManager;
import com.ds.cluster.udp.ClusterEvent;
import com.ds.common.JDSException;
import com.ds.common.query.Condition;
import com.ds.common.query.JLuceneIndex;
import com.ds.common.query.JoinOperator;
import com.ds.common.query.Operator;
import com.ds.common.util.DateUtility;
import com.ds.config.ErrorListResultModel;
import com.ds.config.ListResultModel;
import com.ds.config.ResultModel;
import com.ds.engine.JDSSessionHandle;
import com.ds.enums.db.MethodChinaName;
import com.ds.esb.config.manager.ServiceBean;
import com.ds.esd.admin.node.XUICommandLog;
import com.ds.esd.admin.node.XUIDataLog;
import com.ds.jds.core.esb.EsbUtil;
import com.ds.msg.CommandMsg;
import com.ds.msg.LogMsg;
import com.ds.msg.MsgClient;
import com.ds.msg.MsgFactroy;
import com.ds.org.query.MsgConditionKey;
import com.ds.server.JDSServer;
import com.ds.web.ConnectionLogFactory;
import com.ds.web.RuntimeLog;
import com.ds.web.util.PageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@MethodChinaName(cname = "消息服务")
@RequestMapping("/admin/msg/")
public class MsgService {
    @MethodChinaName(cname = "上报数据日志")
    @RequestMapping(value = {"getSensorCMDLogs"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<XUICommandLog>> getSensorCMDLogs(String sensorieee, String starttime, String endtime) {
        ListResultModel<List<XUICommandLog>> userStatusInfo = new ListResultModel<List<XUICommandLog>>();
        try {
            MsgClient client = MsgFactroy.getInstance().getClient(null, CommandMsg.class);
            Condition<MsgConditionKey, JLuceneIndex> condition = new Condition(MsgConditionKey.MSG_ACTIVITYINSTID, Operator.EQUALS, sensorieee);
            if (starttime != null && !starttime.equals("") && endtime != null && !endtime.equals("")) {
                Condition timeCondition = new Condition(MsgConditionKey.MSG_SENDTIME, Operator.BETWEEN, new Date[]{DateUtility.getDate(starttime), DateUtility.getDate(endtime)});
                condition.addCondition(timeCondition, JoinOperator.JOIN_AND);
            }
            ListResultModel<List<CommandMsg>> commandMsgs = client.getMsgList(condition);
            userStatusInfo = PageUtil.changPageList(commandMsgs, XUICommandLog.class);
        } catch (JDSException e)

        {
            userStatusInfo = new ErrorListResultModel();
            ((ErrorListResultModel) userStatusInfo).setErrcode(e.getErrorCode());
            ((ErrorListResultModel) userStatusInfo).setErrdes(e.getMessage());
        }


        return userStatusInfo;
    }


    @MethodChinaName(cname = "测试发送")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = "testSendEvent")
    public @ResponseBody
    ResultModel<Boolean> testSendEvent(String sessionId, String msg) {
        Integer k = 0;
        while (k < 1000) {

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            ClusterEvent clusterEvent = new ClusterEvent();
            clusterEvent.setMsgId(UUID.randomUUID().toString());
            clusterEvent.setEventId("testente");
            clusterEvent.setSourceJson("" + k);
            clusterEvent.setSessionHandle(new JDSSessionHandle(sessionId));
            clusterEvent.setSessionId("d0daca60-d0ab-4d9a-b20b-4069c05c25eb");
            clusterEvent.setSystemCode("mqtt");
            clusterEvent.setEventName("testEventName");
            clusterEvent.setExpression("$RepeatMqttMsg");
            String eventStr = JSON.toJSONString(clusterEvent);
            boolean isSend = JDSServer.getClusterClient().getUDPClient().send(eventStr);
            k = k + 1;

            System.out.println(clusterEvent.getMsgId());
        }
        return new ResultModel();
    }


    @MethodChinaName(cname = "获取所有可订阅消息")
    @RequestMapping(value = {"getAllEventBeans"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<? extends ServiceBean>> getAllEventBeans() {
        ListResultModel<List<? extends ServiceBean>> userStatusInfo = new ListResultModel<List<?extends ServiceBean>>();
        SysEventWebManager webManager = EsbUtil.parExpression(SysEventWebManager.class);
        List<? extends ServiceBean> serviceBeans = null;
        try {
            serviceBeans = webManager.getRegisterEventByCode("all").get();
        } catch (JDSException e) {
            e.printStackTrace();
        }
        userStatusInfo.setData(serviceBeans);
        return userStatusInfo;
    }


    @MethodChinaName(cname = "命令服务日志")
    @RequestMapping(value = {"getCMDLogs"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<XUICommandLog>> getCMDLogs(String gwieee, String ieee, String starttime, String endtime, String body) {
        ListResultModel<List<XUICommandLog>> userStatusInfo = new ListResultModel<List<XUICommandLog>>();
        try {
            Condition condition = new Condition(MsgConditionKey.MSG_TYPE, Operator.EQUALS, "MSG");
            MsgClient client = MsgFactroy.getInstance().getClient(null, CommandMsg.class);

            //n根据聊天内容 模糊检索
            if (body != null && !body.equals("")) {
                Condition<MsgConditionKey, JLuceneIndex> gwcondition = new Condition(MsgConditionKey.MSG_BODY, Operator.LIKE, "%" + body + "%");
                condition.addCondition(gwcondition, JoinOperator.JOIN_AND);
            }

            //根据发送时间区间检索
            if (endtime != null && !endtime.equals("")) {
                Condition timeCondition = new Condition(MsgConditionKey.MSG_SENDTIME, Operator.LESS_THAN, endtime);
                condition.addCondition(timeCondition, JoinOperator.JOIN_AND);
            }

            if (endtime != null && !endtime.equals("")) {
                Condition timeCondition = new Condition(MsgConditionKey.MSG_SENDTIME, Operator.LESS_THAN, endtime);
                condition.addCondition(timeCondition, JoinOperator.JOIN_AND);
            }



            if (starttime != null && !starttime.equals("")) {
                Condition timeCondition = new Condition(MsgConditionKey.MSG_SENDTIME, Operator.GREATER_THAN, starttime);
                condition.addCondition(timeCondition, JoinOperator.JOIN_AND);
            }


            ListResultModel<List<CommandMsg>> commandMsgs = client.getMsgList(condition);
            userStatusInfo = PageUtil.changPageList(commandMsgs, XUICommandLog.class);
        } catch (
                JDSException e)

        {
            userStatusInfo = new ErrorListResultModel();
            ((ErrorListResultModel) userStatusInfo).setErrcode(e.getErrorCode());
            ((ErrorListResultModel) userStatusInfo).setErrdes(e.getMessage());
        }


        return userStatusInfo;
    }

    @MethodChinaName(cname = "运行日志")
    @RequestMapping(value = {"getRunTimeLogs"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<RuntimeLog>> getRunTimeLogs(String url, String body, String sessionId, Long time) {
        if (time == null) {
            time = 0L;
        }
        if (url == null || url.equals("")) {
            url = "http://";
        }
        ListResultModel<List<RuntimeLog>> userStatusInfo = new ListResultModel<List<RuntimeLog>>();
        List<RuntimeLog> logs = ConnectionLogFactory.getInstance().findLogs(url, body, sessionId, time);
        userStatusInfo = PageUtil.getDefaultPageList(logs);
        return userStatusInfo;
    }


    @RequestMapping(value = {"getUDPLogs"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<RuntimeLog>> getUDPLogs(String url, String body, String sessionId, Long time) {
        if (time == null) {
            time = 0L;
        }
        ListResultModel<List<RuntimeLog>> userStatusInfo = new ListResultModel<List<RuntimeLog>>();
        SysEventWebManager manager = EsbUtil.parExpression(SysEventWebManager.class);
        if (url == null || url.equals("")) {
            url = "udp://";
        } else if (url.endsWith("]")) {
            url = url.substring(0, url.lastIndexOf(":"));
        }
        ListResultModel<List<RuntimeLog>> logs = manager.getRunTimeLogs(url, body, sessionId, time);
        userStatusInfo = PageUtil.changPageList(logs, RuntimeLog.class);
        return userStatusInfo;
    }


    @RequestMapping(value = {"clearUDPServer"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> clearUDPServer(String url) {
        ConnectionLogFactory.getInstance().clear(url);
        ResultModel userStatusInfo = new ResultModel();
        return userStatusInfo;
    }

    @RequestMapping(value = {"clearLocalLog"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> clearLocalLog(String url) {
        ConnectionLogFactory.getInstance().clear(url);
        ResultModel userStatusInfo = new ResultModel();
        return userStatusInfo;
    }


    @MethodChinaName(cname = "UPD集群广播")
    @RequestMapping(value = {"getLocalUDPLogs"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<RuntimeLog>> getLocalUDPLogs(String url, String body, String sessionId, Long time) {
        if (time == null) {
            time = 0L;
        }
        ListResultModel<List<RuntimeLog>> userStatusInfo = new ListResultModel<List<RuntimeLog>>();
        if (url == null || url.equals("")) {
            url = "udp://";
        } else if (url.endsWith("]")) {
            url = url.substring(0, url.lastIndexOf(":"));
        }
        List<RuntimeLog> logs = ConnectionLogFactory.getInstance().findLogs(url, body, sessionId, time);
        userStatusInfo = PageUtil.getDefaultPageList(logs, RuntimeLog.class);
        return userStatusInfo;
    }


    @RequestMapping(value = {"clear"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> clear(String url) {
        ConnectionLogFactory.getInstance().clear(url);
        ResultModel userStatusInfo = new ResultModel();
        return userStatusInfo;
    }


    @MethodChinaName(cname = "获取数据日志")
    @RequestMapping(value = {"getDataLogs"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<XUIDataLog>> getDataLogs(String gwieee, String ieee, String starttime, String endtime, String body) {
        ListResultModel<List<XUIDataLog>> userStatusInfo = new ListResultModel<List<XUIDataLog>>();
        Condition condition = new Condition(MsgConditionKey.MSG_TYPE, Operator.EQUALS, "LOG");
        try {
            List<XUIDataLog> modules = new ArrayList<XUIDataLog>();
            MsgClient<LogMsg> client = MsgFactroy.getInstance().getClient(null, LogMsg.class);

            if (gwieee != null && !gwieee.equals("")) {
                Condition<MsgConditionKey, JLuceneIndex> gwcondition = new Condition(MsgConditionKey.MSG_PROCESSINSTID, Operator.EQUALS, gwieee);
                condition.addCondition(gwcondition, JoinOperator.JOIN_AND);
            }

            if (ieee != null && !ieee.equals("")) {
                Condition<MsgConditionKey, JLuceneIndex> gwcondition = new Condition(MsgConditionKey.MSG_ACTIVITYINSTID, Operator.EQUALS, ieee);
                condition.addCondition(gwcondition, JoinOperator.JOIN_AND);
            }

            if (body != null && !body.equals("")) {
                Condition<MsgConditionKey, JLuceneIndex> gwcondition = new Condition(MsgConditionKey.MSG_BODY, Operator.LIKE, "%" + body + "%");
                condition.addCondition(gwcondition, JoinOperator.JOIN_AND);
            }

            if (endtime != null && !endtime.equals("")) {
                Condition timeCondition = new Condition(MsgConditionKey.MSG_SENDTIME, Operator.LESS_THAN, endtime);
                condition.addCondition(timeCondition, JoinOperator.JOIN_AND);
            }

            if (starttime != null && !starttime.equals("")) {
                Condition timeCondition = new Condition(MsgConditionKey.MSG_SENDTIME, Operator.GREATER_THAN, starttime);
                condition.addCondition(timeCondition, JoinOperator.JOIN_AND);
            }


            ListResultModel<List<LogMsg>> commandMsgs = client.getMsgList(condition);

            userStatusInfo = PageUtil.changPageList(commandMsgs, XUIDataLog.class);

        } catch (
                JDSException e)

        {
            userStatusInfo = new ErrorListResultModel();
            ((ErrorListResultModel) userStatusInfo).setErrcode(e.getErrorCode());
            ((ErrorListResultModel) userStatusInfo).setErrdes(e.getMessage());
        }


        return userStatusInfo;
    }


}
